package net.javamine.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 文件工具类
 * @author <a href="mailto: java_lht@163.com">Lht</a>
 * @since 2012-5-24 1.create
 * @version 1.0
 */
public class FileUtils {

	/**
	 * 文件上传 (spring mvc 3 注解方式的文件上传)
	 * 
	 * 使用之前需在springmvc-servlet.xml文件中添加： <bean id="multipartResolver" class=
	 * "org.springframework.web.multipart.commons.CommonsMultipartResolver" />
	 * 
	 * jsp页面form中需加属性：enctype="multipart/form-data"
	 * 
	 * @param request
	 *            controller方法中的参数为：@RequestParam(value = "cat_filePath",
	 *            required = false) MultipartFile file
	 * 
	 *            页面中的文本框name属性的值为cat_filePath
	 * 
	 * @param targetPath
	 *            文件上传目标路径，不包括文件名
	 * 
	 *            例如：String targetPath =
	 *            request.getSession().getServletContext()
	 *            .getRealPath("upload"); upload为最后一级文件夹名称 实际产生的路径为：E:\Apache
	 *            Software Foundation\Tomcat 6.0\webapps\mms\ upload
	 * 
	 *            使用String filePath =
	 *            request.getContextPath()+"/upload/"+fileName;
	 *            语句可以在controller中获得可以在页面展示的路径 如：/mms/upload/文件名.扩展名
	 * 
	 * @return fileNames 文件名
	 */
	public static List<String> fileUpload(HttpServletRequest request,
			String targetPath) {
		List<String> fileNames = new ArrayList<String>();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			File targetFile = new File(targetPath);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
				MultipartFile mf = entry.getValue();
				fileNames.add(mf.getOriginalFilename());
				File uploadFile = new File(targetPath + "\\" + fileNames);
				FileCopyUtils.copy(mf.getBytes(), uploadFile);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return fileNames;
	}

	/**
	 * 下载文件
	 * 
	 * @param response
	 * @param srcPath
	 *            需要下载的文件的完整物理路径，包括文件名
	 * @param encode
	 *            编码格式：UTF-8/GBK...
	 */
	public static void fileDownload(HttpServletResponse response,
			String srcPath, String encode) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			String fileName = StringUtils.getFilename(srcPath);
			response.setCharacterEncoding(encode);
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName="
					+ fileName);
			File file = new File(srcPath);
			inputStream = new FileInputStream(file);
			outputStream = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				outputStream.write(b, 0, length);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null)
					inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (outputStream != null)
						outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 写文本文件（区别于图片等格式的文件）
	 * 
	 * @param filePath
	 *            文件路径
	 * @param list
	 *            每一行內容为list中的一个元素
	 */
	public static void writeFile(String filePath, List<String> list) {
		File file = null;
		FileWriter fileWriter = null;
		try {
			file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			fileWriter = new FileWriter(file);
			for (String line : list) {
				fileWriter.write(line);
				fileWriter.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileWriter != null) {
					fileWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 读文本文件
	 * @param file 需要读取的文件
	 * @return list 每行内容为list的一个元素
	 */
	public static List<String> readFile(File file) {
		FileReader fr = null;
		BufferedReader br = null;
		List<String> list = new ArrayList<String>();
		try {
			fr = new FileReader(file);
			br = new BufferedReader(fr);
			String line = "";
			while ((line = br.readLine()) != null) {  
				StringBuffer sb = new StringBuffer();
				sb.append(line);
				sb.append("\n");
				list.add(sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fr != null) fr.close();
				if (br != null) br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 * 文件名不能包含 \/:*?"<>| ，所以一旦出现，则将其替换为空格
	 * 
	 * @param fileName
	 * @return
	 */
	public static String fileNameReplace(String fileName) {
		if (fileName == null)
			return null;
		String s = "\\ / : * ? \" < > |";
		String[] ss = s.split(" ");
		for (String l : ss) {
			fileName = fileName.replaceAll("\\" + l, "");
		}
		return fileName;
	}

}
